﻿/*                              
   Copyright 2011 Nils Kopal, Christopher Krüger, Simone Sauer, Dennis Nolte, Uni Duisburg-Essen

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sharebert.LinkLayerLibrary.API;

namespace Sharebert.LinkLayerLibrary
{
    public class Header : IHeader
    {
        private const string PROTOCOL_IDENT = "SB";

        private const string LENGTH_PARAMETER = "Length";


        #region Constructor

        /// <summary>
        /// Initializes a new instance of the Header class used by network messages.
        /// This constructor is used for deserialization.
        /// </summary>
        public Header()
            : this(null, 0)
        {
        }

        /// <summary>
        /// Initializes a new instance of the Header class used by network messages.
        /// This constructor is used for serialization.
        /// </summary>
        public Header(string command, long payloadLength)
        {
            this.Command = command;
            this.PayLoadLength = payloadLength;
        }

        #endregion


        private enum HeaderState
        {
            Command,

            Length,
            // add other obligatory elements here

            End
        }

        /// <summary>
        /// Parses a network header. Unknown lines of the header will be ignored.
        /// </summary>
        /// <param name="header">The string containing the header</param>
        /// <exception cref="System.ArgumentNullException">header is null</exception>
        /// <exception cref="Sharebert.LinkLayerLibrary.HeaderException">Invalid header format</exception>
        public void Parse(string header)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            HeaderState state = HeaderState.Command;
            string[] lines = header.Split('\n');

            // Parse each line separatly
            foreach (string line in lines)
            {
                switch (state)
                {
                    case HeaderState.Command:
                        this.Command = ParseCommand(lines[0]);
                        state = HeaderState.Length;
                        break;
                    case HeaderState.Length:
                        this.PayLoadLength = ParsePayloadLength(lines[1]);
                        state = HeaderState.End;
                        break;
                    // Other header lines may coming...
                    default:
                        break;
                }
            }
        }

        private string ParseCommand(string s)
        {
            string[] line = s.Split(' ');
            if (line.Length < 2)
            {
                throw new HeaderException("Invalid header! First line of the header is no 2 tuple!");
            }
            if (!line[0].Equals(PROTOCOL_IDENT))
            {
                throw new HeaderException("Invalid header! No ShareBert identifier!");
            }
            return line[1];
        }

        private long ParsePayloadLength(string s)
        {
            string[] secondLine = s.Split(':');
            if (secondLine.Length < 2)
            {
                throw new HeaderException("Invalid header! Second line of the header is no 2 tuple!");
            }
            if (secondLine[0].Trim().ToLower() != LENGTH_PARAMETER.ToLower())
            {
                throw new HeaderException("Invalid header! Second line of the header does not contain the payload length!");
            }
            long length;
            if (!Int64.TryParse(secondLine[1].Trim(), out length))
            {
                throw new HeaderException("Invalid header! No message length specified!");
            }
            return length;
        }

        /// <summary>
        /// The network header used for sending packets (without trailing \n).
        /// </summary>
        /// <returns>A string containing the formated header</returns>
        public string GetHeader()
        {
            return PROTOCOL_IDENT + " " + this.Command + "\n"
                + "Length: " + this.PayLoadLength;
        }

        /// <summary>
        /// ToString representation of the header, used for debugging.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("### ShareBert Header ### ");
            sb.Append("Command:    ").AppendLine(this.Command);
            sb.Append("Length:     ").AppendLine(this.PayLoadLength.ToString());
            return sb.ToString();
        }


        #region Properties and private members

        /// <summary>
        /// The command or message type of the message.
        /// </summary>
        public string Command { get; private set; }

        /// <summary>
        /// The number of bytes of the payload.
        /// </summary>
        public long PayLoadLength { get; private set; }

        #endregion

    }
}
